<?PHP

 if (isset($_POST['invalid']) || isset($_POST['fixed']) || isset($_POST['new']) || isset($_POST['prune'])) {
  // We need to be able to redirect.

  set_time_limit(0);
  ob_start();
 }

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
 <head>
  <title>DMDirc :: Admin</title>
  <link rel="stylesheet" type="text/css" href="/res/style.css">
  <style type="text/css">
   table {
    width: 100%;
    border-collapse: collapse;
   }
   td, th {
    border: 1px solid #666;
   }
   th {
    text-align: center;
   }
  </style>
 </head>
 <body>
  <div id="container">
   <img id="logo" src="/res/logo.png" alt="DMDirc logo">
   <h1>DMDirc</h1>
<?PHP require_once('admin-menu.php'); ?>
   <div id="content">
<?php

 require_once('../inc/sqlite.php');

 if (!$db = sqlite_open('data.db', 0777, $sqliteerror)) {
  die($sqliteerror);
 }

 if (!sqlite_table_exists($db, 'errors')) {
  die('Error table doesn\'t exist');
 }

 $prev = array();
 $errors = array();

 $sql = 'SELECT id, message, trace, version, ip, status FROM errors';
 $res = sqlite_query($sql, $db);
 while ($row = sqlite_fetch_array($res)) {
  $trace = substr($row['trace'], 1, -1);
  $trace = str_replace(', ', "\n", $trace);
  $source = '';

  foreach (explode("\n", $trace) as $line) {
   if (strpos($line, 'com.dmdirc') === 0) {
    $source = preg_replace('/^(.*)\\.([^\\.]+)\(.*$/', '\1', substr($line, 11)); 
    break;
   }
  }

  $sig = md5($row['message'] . implode('', array_slice(explode("\n", $trace), 0, 3)));
  
  if (isset($prev[$sig])) {
   $errors[$prev[$sig]]['versions'][$row['version']]++;
   $errors[$prev[$sig]]['ips'][$row['ip']]++;
   $errors[$prev[$sig]]['reports'][] = $row['id'];
  } else {
   $errors[$row['id']] = array(
    'message' => $row['message'],
    'source' => $source,
    'trace' => $row['trace'],
    'status' => $row['status'],
    'versions' => array($row['version'] => 1),
    'ips' => array($row['ip'] => 1),
    'reports' => array($row['id'])
   );
   $prev[$sig] = $row['id'];
  }
 }

 $status = false;
 if (isset($_POST['new'])) { $status = 'new'; } 
 if (isset($_POST['fixed'])) { $status = 'fixed'; }
 if (isset($_POST['invalid'])) { $status = 'invalid'; }
 if ($status !== false) {
  $sql = 'UPDATE errors SET status = \'' . $status . '\' WHERE 0';
  foreach ($_POST as $k => $v) {
   if (substr($k, 0, 6) == 'error_') {
    $id = (int) substr($k, 6);
    foreach ($errors[$id]['reports'] as $error) {
     $sql .= ' OR id = ' . $error;
    }
   }
  }
  sqlite_query($sql, $db);
  header('Location: ' . $_SERVER['REQUEST_URI']);
  exit;
 }

 if (isset($_POST['prune'])) {
  $sql  = 'DELETE FROM errors WHERE (status = \'fixed\' OR status = \'invalid\')';
  $sql .= ' AND time < ' . strtotime('-1 month');
  $res  = sqlite_query($sql, $db);
  echo "Pruned ", sqlite_changes($db), " rows.";
 }


 if (isset($_POST['show_fixed'])) {
  $status = 'fixed';
 } elseif (isset($_POST['show_invalid'])) {
  $status = 'invalid';
 } else {
  $status = 'new';
 }

 foreach ($errors as $id => $data) {
  if ($data['status'] != $status) {
   unset($errors[$id]);
  }
 }


?>
    <h2>Error Summary</h2>
    <form action="errors" method="post">
    <table>
     <tr>
      <th></th>
      <th>ID</th>
      <th>Error</th>
      <th>Source</th>
      <th colspan="3">Reports</th>
     </tr>
<?PHP
 foreach ($errors as $id => $error) {
  $title = strlen($error['message']) > 53 ? substr($error['message'], 0, 50) . '...' : $error['message'];
?>
     <tr>
      <td><input type="checkbox" name="error_<?PHP echo $id; ?>"></td>
      <td><?PHP echo $id; ?></td>
      <td>
       <a href="#error<?PHP echo $id; ?>">
        <?PHP echo htmlentities($title); ?>
       </a>
      </td>
      <td><?PHP echo htmlentities($error['source']); ?></td>
      <td title="Total reports"><?PHP echo count($error['reports']); ?></td>
      <td title="Number of involved versions"><?PHP echo count($error['versions']); ?></td>
      <td title="Number of involved IP addresses"><?PHP echo count($error['ips']); ?></td>
     </tr>
<?PHP
 }
?>
    </table>
    <br>
    <input type="submit" name="invalid" value="Mark selected as invalid">
    <input type="submit" name="fixed" value="Mark selected as fixed">
    <input type="submit" name="new" value="Mark selected as new">
    ||
    <input type="submit" name="show_invalid" value="Show invalid issues">
    <input type="submit" name="show_fixed" value="Show fixed issues">
    <input type="submit" name="show_new" value="Show new issues">
    ||
    <input type="submit" name="prune" value="Prune old issues">
    </form>
    <h2>Error Details</h2>
<?PHP
 foreach ($errors as $id => $error) {
?>
    <h3 id="error<?PHP echo $id; ?>"><?PHP echo htmlentities($error['message']); ?></h3>
    <p>
<?PHP if (count($error['reports']) > 1) { ?>
     There have been <?PHP echo count($error['reports']); ?> reports of this error,
<?PHP } else { ?>
     There has been 1 report of this error,
<?PHP } ?>
     originating from <?PHP echo count($error['versions']); ?> distinct
     version<?PHP echo count($error['versions']) > 1 ? 's' : ''; ?>
     and <?PHP echo count($error['ips']); ?> distinct IP
     address<?PHP echo count($error['ips']) > 1 ? 'es' : ''; ?>.
    </p>
<pre><?PHP echo str_replace(", ", "\n", substr($error['trace'], 1, -1)); ?></pre>
    <table style="table-layout: fixed;">
     <tr><th colspan="2">Versions</th><th colspan="2">IP Addresses</th></tr>
<?PHP

 $lines = array();
 $i = 0;
 foreach ($error['versions'] as $v => $c) { $lines[$i++][0] = array($v, $c); }
 $i = 0;
 foreach ($error['ips'] as $v => $c) { $lines[$i++][1] = array($v, $c); }

 foreach ($lines as $data) {
  echo '<tr>';
  if (isset($data[0])) {
   echo '<td>' . htmlentities($data[0][0]) . '</td>'; 
   echo '<td>' . $data[0][1] . '</td>';
  } else {
   echo '<td></td><td></td>';
  }

  if (isset($data[1])) {
   echo '<td>' . htmlentities($data[1][0]) . '</td>';
   echo '<td>' . $data[1][1] . '</td>';
  } else {
   echo '<td></td><td></td>';
  }
  echo '</tr>';
 }
?>
    </table>
    <p style="text-align: right;">
     <small><a href="#content">Back to summary</a></small>
    </p>
<?PHP
 }
?>
   </div>
   <div id="footer">
   </div>
  </div>
 </body>
</html>
